/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.commons.cryptography.providers;

import io.iec.edp.caf.commons.cryptography.model.CafKeyPair;
import io.iec.edp.caf.commons.cryptography.service.AsymmetricCryptoProvider;

import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * DSA签名与验签
 *
 * @author guowenchang
 */
public class DSACryptoProvider implements AsymmetricCryptoProvider {

    public static final int KEY_SIZE = 512;
    public static final String ALGORITHM = "DSA";

    @Override
    public CafKeyPair generateKeyPair() {
        try {
            //DSA算法要求有一个可信任的随机数源
            SecureRandom secureRandom = new SecureRandom();
            ///为DSA算法创建一个KeyPairGenerator对象
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM);
            // 初始化密钥对生成器，并设置密钥长度
            keyPairGen.initialize(KEY_SIZE, secureRandom);
            // 生成一个密钥对，保存在keyPair中
            KeyPair keyPair = keyPairGen.generateKeyPair();
            return new CafKeyPair(keyPair);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("generate key failed.");
        }
    }

    @Override
    public byte[] encrypt(byte[] byteIn, byte[] key,boolean isReverse) {
        throw new RuntimeException("DSA does not support this method");
    }

    @Override
    public byte[] decrypt(byte[] byteIn, byte[] key,boolean isReverse) {
        throw new RuntimeException("DSA does not support this method");
    }

    @Override
    public byte[] sign(byte[] byteIn, byte[] key) {
        try {
            // 将byte[]的key格式化为PrivateKey
            PrivateKey privateKey = KeyFactory.getInstance(ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(key));
            // 获取算法实例并初始化
            Signature signature = Signature.getInstance(ALGORITHM);
            signature.initSign(privateKey);
            signature.update(byteIn);
            return signature.sign();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("sign failed.");
        }
    }

    @Override
    public boolean verify(byte[] byteIn, byte[] sign, byte[] key) {
        try {
            // 取公钥匙对象
            PublicKey publicKey = KeyFactory.getInstance(ALGORITHM).generatePublic(new X509EncodedKeySpec(key));
            Signature signature = Signature.getInstance(ALGORITHM);
            signature.initVerify(publicKey);
            signature.update(byteIn);
            // 验证签名是否正常
            return signature.verify(sign);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
